<?php

namespace Trawind\Helpers;


use File;
use Illuminate\Support\Str;
use Swoole\Coroutine;
use Illuminate\Redis\RedisManager;
use Illuminate\Support\Facades\Redis;
use Trawind\Basics\Enums\BusinessType;
use TrawindCloud\Providers\RepositoryServiceProvider;

class SystemHelper
{

    public static function isSystemEnv()
    {
        return app('env') == 'system1';
    }


    public static function isDevelopEnv()
    {
        return app('env') == 'develop';
    }


    public static function isSomeService(string $service)
    {
        return config('app.name') == $service;
    }


    public static function runningInConsole()
    {
        return app()->runningInConsole() && Coroutine::getuid() < 0;
    }


    public static function getTenantFilePath(string $file_path = '')
    {
        $filePath = storage_path($file_path);
        $pathArr = explode('/', $filePath);
        $endPath = array_pop($pathArr);
        $dirPath = Str::contains($endPath, '.') ? Str::replaceFirst('/'.$endPath, '', $filePath) : $filePath;

        if (!File::isFile($filePath)) {
            if (!File::isDirectory($dirPath)) {
                File::makeDirectory($dirPath, 0755, true);
            }
        }
        return storage_path($file_path);
    }


    public static function image2base64(string $image_file)
    {
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'rb'), filesize($image_file));
        return 'data:'.$image_info['mime'].';base64,'.chunk_split(base64_encode($image_data));
    }


    /**
     * @return \Redis
     */
    public static function redis()
    {
        return app()->make('common_redis');
//        $key = 'commonRedis';
//        if (!app()->has($key)) {
//            app()->singleton($key, function ($app) {
//                $config = config('database.redis');
//                $config['options']['prefix'] = '';
//                return new RedisManager(app(), 'phpredis', $config);
//            });
//        }
//
//        return app($key);
    }

    /**
     * @param $businessTypeId
     * @return string
     */
    public static function getBusinessTypeEloquent($businessTypeId)
    {
        if (property_exists(RepositoryServiceProvider::class,
                'businessTypeMap') && isset(RepositoryServiceProvider::$businessTypeMap[$businessTypeId])) {
            return RepositoryServiceProvider::$businessTypeMap[$businessTypeId];
        } else {
            return BusinessType::REMOTE_MAP[$businessTypeId];
        }
    }

}